(ns liberator-sample.core.documentation.decisions
  (:require [liberator.core :refer [defresource resource]]
            [compojure.core :refer [defroutes ANY GET]]
            [liberator.dev :refer [wrap-trace]]
            [ring.middleware.params :refer [wrap-params]]
            [ring.middleware.reload :refer [wrap-reload]]
            [org.httpkit.server :as server]
            [clojure.java.io :as io]
            [clojure.data.json :as json]
            [taoensso.timbre :refer [spy]])
  (:use clojure.pprint))

(defn wrap-request-accept [handler]
  (fn [req]
    ;(println "----------" :request-accept (:uri req) "----------")
    (let [resp (handler req)]
      ;(println "----------" :request-done "----------")
      resp)))

;(defn resource [& kvs]
;  (println :resource)
;  (prn kvs)
;  (fn [request]
;    (run-resource request (get-options kvs))))

(def entries (ref {"1" "a"
                   "2" "b"
                   "3" "C"}))

(declare aresource app id)
(defresource aresource [id]
             :available-media-types ["text/html" "text/plain"]
             :allowed-methods [:get]
             :handle-ok "not ok")

(defroutes app
           (GET "/ring" [] "ok")
           (ANY "/a/:id" [id] (aresource id))
           (ANY "/entries/:id" [id]
                (resource
                  :available-media-types ["text/html" "text/plain"]
                  :allowed-methods [:get :put :delete]
                  :exists? (fn [_]
                             (println :exists?)
                             (let [e (get @entries id)]
                               (if-not (nil? e)
                                 {::entry e})))
                  :existed? (fn [_]
                              (println :existed?)
                              (spy (nil? (get @entries id ::sentinel))))
                  :handle-ok ::entry
                  :delete! (fn [_]
                             (println :delete!)
                             (dosync (alter entries assoc id nil)))
                  :put! #(do
                          (println :put!)
                          (dosync (alter entries assoc id (::data %))))
                  :new? (fn [_]
                          (println :new?)
                          (nil? (get @entries id ::sentinel))))))
